<?php
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Verjaardag</title>
<link href="opmaak.css" rel="stylesheet" type="text/css" media="screen" />

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

<script type="text/javascript">
	$(document).ready(function(){
	
	$("form").css({ "margin-left" : "10px" });
	$("form div").css({ "display" : "none" });
	$("form div:first").css({ "display" : "block" });
	
	$(".vorig").click(function(){
		$(this).parent().css({ "display" : "none" });
		$(this).parent().prev().css({ "display" : "block" });
	});
	$(".volgend").click(function(){
		$(this).parent().css({ "display" : "none" });
		$(this).parent().next().css({ "display" : "block" });
		
	});
	
	});
	function laadscherm()
	{
 		$('#content').hide();
		$('body').append('<img src="http://www.club-connect.nl/hyvessync/images/loading.gif" title="loading" alt="loading" />')
	}
</script>
</head>
<body>
<?php 
require_once('GenusAPIs/GenusApis.php');
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Gdata');
Zend_Loader::loadClass('Zend_Gdata_AuthSub');
Zend_Loader::loadClass('Zend_Gdata_ClientLogin');
Zend_Loader::loadClass('Zend_Gdata_Calendar');

	include('database_inc.php');
	$db = mysqli_connect($server,$gebruikersnaam, $password);
	mysqli_select_db($db, $database);
	
	if(!isset($_POST['bevestigen']))
	{
	?>
    <div id="content"> 
    <div id="headert"><table><tr><td><img src="images/hyvessynclogo.png" title="HyvesSync" alt="HyvesSync" /></td><td><label class="title">HyvesSync</label></td></tr></table></div>
    <p>Selecteer hier de vrienden waarvan je wilt dat de verjaardagen in je Google Agenda komt. Je ziet er maximaal 20 tegelijk.</p>
    <?php
 
	// Declare oauth_consumer
 		$oOAuthConsumer = new OAuthConsumer("MjEwNV-jK9CigmbdQ_zJa-FU8qDy", "MjEwNV_8vv9S3vRZwSLVItIrsZwu");

		$sql = "SELECT * FROM users WHERE hyvesID = '".$_SESSION['hyvesid']."' ";
				$result2 = mysqli_query($db, $sql);
				$regel2 = mysqli_fetch_array($result2);
				$oAccessToken = unserialize($regel2['hyvesAccessTokenObject']);

		// Init GenusApis
 		$oGenusApis = new GenusApis($oOAuthConsumer);
		$sParam = array();
			
	    //retrieve friends from hyves and get data
		$oXmlResult = $oGenusApis->doMethod("friends.get", $sParam, $oAccessToken);
		$i = 0;
		$sParam2 = array();
		//create form checkboxes to select friends and birthdays
		echo "<form action='bday.php' method='post' name='selectie'>";

		//loop through the code that retrieves the data required (day and month of birth, firstname of friend and the age of the friend)
		foreach ($oXmlResult->userid as $friend) 
		{
			$sParam2['userid'] .= $friend.',';
	  	}
		$sParam2['userid'] = trim($sParam2['userid'], ",");
		
		$oXmlResult2 = $oGenusApis->doMethod("users.get", $sParam2, $oAccessToken);
		
		$limit = (int) count($oXmlResult2->user);
		
		for ($k = 1; $k <= ceil($limit/20); $k++)
		{
			echo "<div id='".$k."'><p>pagina ".$k." van de ".ceil($limit/20)."</p>";
			for ($s = ($k-1)*20; $s < $k*20; $s++)
			{
			$friend = $oXmlResult2->user[$s];
			//state variables for day and month of birth, firstname and age of friend
			$naam = $friend->firstname;
			$dag = (string)$friend->birthday->day;
			$maand = (string)$friend->birthday->month;
			$ltijd = (string)$friend->birthday->age;	
				//display a checkbox and the name and other data of friends on screen
				if($dag != "" && $maand !="")
				{
					echo "<input type='checkbox' name='bday".$i++."' value='".$naam."-".$dag."-".$maand."-".$ltijd."'>"; 
					echo $naam;
					echo " ".$dag."/";
					echo $maand."<br>";
		
				}
				elseif($dag == "" && $maand == "" && $naam != "")
				{
						echo $naam." ";
						echo "heeft geen verjaardag opgegeven <br>";
				}
			}
			if ($k == 1)
			{
			echo "<br />Vorige || <a class='volgend' id='volgend".$k."' href='#volgend".$k."'>Volgende</a>";
			echo "</div>";
			}
			elseif ($k == ceil($limit/20))
			{
			echo "<br /><a class='vorig' id='vorig".$k."' href='#vorig".$k."'>Vorige</a> || Volgende";
			echo "</div>";
			}
			else
			{
			echo "<br /><a class='vorig' id='vorig".$k."' href='#vorig".$k."'>Vorige</a> || <a class='volgend' id='volgend".$k."' href='#volgend".$k."'>Volgende</a>";
			echo "</div>";
			}
		}
 	?>
    							<br />
   								 <select name="Reminder" size="1">
									  <option value="sms">sms</option>
									  <option value="email">email</option>
									  <option value="alert">alert</option>
									  <option value="none" selected="selected">none</option>
								</select>
								
									<input id="Tijdje" type="text" name="Tijd">
									
								<select name="Time">
									   <option value="Minutes">Minuten</option>
									   <option value="Hours">Uren</option>
									   <option value="Days">Dagen</option>
							    </select>
    <?php
//close all loops and make submit button
    
    echo "<br /><input type='submit' value='Vrienden toevoegen' name='bevestigen' onclick='laadscherm()'>";
	
	}
	else
	{
		function createEvent ($client, $title = 'Tennis with Beth',
					$desc='Meet for a quick lesson', $where = 'On the courts',
					$startDate = '2009-03-04', $startTime = '10:00',
					$endDate = '2009-03-04', $endTime = '11:00', $tzOffset = '+00', $remindert, $tijd, $time)
				{
						  $gdataCal = new Zend_Gdata_Calendar($client);
						  $newEvent = $gdataCal->newEventEntry();	
				
						  $newEvent->title = $gdataCal->newTitle($title);
						  $newEvent->where = array($gdataCal->newWhere($where));
						  $newEvent->content = $gdataCal->newContent("$desc");
						  
						 $when = $gdataCal->newWhen();
						 $when->startTime = "{$startDate}T{$startTime}:00.000{$tzOffset}:00";
						 $when->endTime = "{$endDate}T{$endTime}:00.000{$tzOffset}:00";
											  
						  $reminder = $gdataCal->newReminder();
    					  $reminder->setMethod($remindert);
						    if ($time == 'Minutes')
							  {
							  	$reminder->setMinutes($tijd);
							  }
						  if ($time == 'Hours')
							  {
							  	$reminder->setHours($tijd);
							  }
						  if ($time == 'Days')
							  {
							  	$reminder->setDays($tijd);
							  }
   						  $when->reminders = array($reminder); 
						  $newEvent->when = array($when);
			
						  // Upload the event to the calendar server
						  // A copy of the event as it is recorded on the server is returned
						  $createdEvent = $gdataCal->insertEvent($newEvent, $kalender);
						  return $createdEvent->id->text;
				}
		for($i = 0;$i < count($_POST)-1; $i++)
		{
		  $values = array_values($_POST);
		  $data = explode('-', $values[$i]);
		  	$naam	= $data[0]; 	
			$dag	= (int)	$data[1];
			$maand	= (int)	$data[2];
			$ltijd	= $data[3];
			if ($maand < 10)
			{
				$maand = '0'.$maand; 
			}
			if ($dag < 10)
			{
				$dag = '0'.$dag; 
			}
			
			for($a= 0;$a <20; $a++)
			{
			$jaar   =	date('Y')+$a;
			$ltijd++;	
			$Bdatum = $jaar.'-'.$maand.'-'.$dag;
			
			$sql = "SELECT * FROM users WHERE hyvesID = '".$_SESSION['hyvesid']."' ";
			$result2 = mysqli_query($db, $sql);
			$regel2 = mysqli_fetch_array($result2);
			
			$client = Zend_Gdata_AuthSub::getHttpClient($regel2['googleAuthSubToken']);
			// getting EventID and breaking up the url
			$EventID = createEvent($client, "Verjaardag $naam","$naam is jarig en wordt $ltijd jaar", "Bij $naam thuis is er misschien feest","$Bdatum", "00:00", "$Bdatum","23:59", '+02', $_POST['Reminder'], $_POST['Tijdje'], $_POST['Time'] );
		 
			  
			}
		
		}
		?>
        <div id="content">
		<div id="headert"><table><tr><td><img src="images/hyvessynclogo.png" title="HyvesSync" alt="HyvesSync" /></td><td><label class="title">HyvesSync</label></td></tr></table></div>
        <p>Het toevoegen van de verjaardagen van je vrienden is gelukt.</p>
        <?php
	}
	
?>
<p><a href="index1.php" onclick="laadscherm()">Ga terug</a></p>
</div>
</body>
</html>